const url_config = require('../../common/config');
var that;
var app = getApp();
var innerAudioContext = null;
var isVoicePlaying = false;
var lastPlayedVoiceUrl = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    'fileUrl': url_config.url_microFileService,
    question: {},
    replybean: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    //得到上个页面的问题条目对象
    let current_question = JSON.parse(options.current_question);
    let title = current_question.process_state == 2 ? '回复详情' : '提问详情';
    wx.setNavigationBarTitle({
      title: title,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
    current_question.create_time_str = that.paseCreateTime(current_question.create_time);
    if (current_question.process_state == 2) {
      that.getQuestionReplyDetail(current_question.qid);
    }
    that.setData({
      question: current_question
    });
    that.registerAudioContext(); //注册声乐播放器
  },

  // 注册音频

  registerAudioContext: function() {
    isVoicePlaying = false;
    lastPlayedVoiceUrl = null;
    that.innerAudioContext = wx.createInnerAudioContext();

    that.innerAudioContext.onPlay((res) => {
      console.log('开始播放');
      isVoicePlaying = true;
      wx.showToast({
        title: '正在播放',
      })

    });
    that.innerAudioContext.onWaiting((res) => {
      console.log('缓冲中');
      isVoicePlaying = true;
    });
    that.innerAudioContext.onEnded((res) => {
      console.log('自然播放至结束');
      isVoicePlaying = false;
      wx.showToast({
        title: '播放完毕',
      })
    });
    that.innerAudioContext.onStop((res) => {
      console.log('音频停止');
      isVoicePlaying = false;
      wx.showToast({
        title: '音频停止',
      })
    });
    that.innerAudioContext.onError((res) => {
      // 播放音频失败的回调
      wx.showToast({
        title: '播放失败',
      })
      console.log('播放音频失败' + JSON.stringify(res));
      isVoicePlaying = false;
      that.innerAudioContext.destroy();
			that.registerAudioContext();
    });
  },

  getQuestionReplyDetail: function(qid) {
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: url_config.url_getQuestionReplyDetail,
      method: 'POST',
      data: {
        qid: qid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'uidusernamekey': app.globalData.userInfo.token
      },
      success: function(res) {
        let resData = res.data;
        if (resData.status == 200) {
          let replyobj = resData.data;
          replyobj.create_time_str = that.paseCreateTime(replyobj.create_time);
          //将图片字符串转换为数组
          if (replyobj.rimgs) {
            let img_arr = replyobj.rimgs.split(",");
            if (img_arr) {
              for (let i = 0; i < img_arr.length; i++) {
                img_arr[i] = that.data.fileUrl + img_arr[i];
              }
              replyobj.rimgs = img_arr;
            }
          }
          //解析录音时长
          let record = replyobj.record;
          if (record) {
            let jsonRecord = JSON.parse(record);
            if (jsonRecord) {
              jsonRecord.duration = parseInt(jsonRecord.duration / 1000);
              replyobj.record = jsonRecord;
            } else {
              replyobj.record = '';
            }
          }
          that.setData({
            replybean: replyobj
          });
        } else {
          wx.showModal({
            title: '提示',
            content: resData.msg,
          })
        }
      },
      fail: function() {
        wx.showModal({
          title: '提示',
          content: '获取回复数据失败',
          confirmText: '再试一次',
          success: function(res) {
            if (res.confirm) {
              that.getQuestionReplyDetail(qid);
            }
          }
        })
      },
      complete: function() {
        wx.hideLoading();
      }
    })
  },
  paseCreateTime: function(create_time) {
    create_time = create_time.length == 13 ? create_time : create_time * 1000;
    var date = new Date(create_time);
    let result_time = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + (String(date.getMinutes()).length == 1 ? '0' + date.getMinutes() : date.getMinutes()) + ':' + date.getSeconds();
    return result_time;
  },
  previewImage: function(e) {
    console.log(e)
    let imgpath = e.currentTarget.dataset.imgpath;
    let type = e.currentTarget.dataset.type;
    let image_arr = type == 'reply' ? that.data.replybean.rimgs : that.data.question.qimgs;
    wx.previewImage({
      current: imgpath, // 当前显示图片的http链接
      urls: image_arr // 需要预览的图片http链接列表
    })
  },

  onUnload: function() {
    that.innerAudioContext.pause();
    wx.setNavigationBarTitle({
      title: '提问历史',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 播放录音
  playRecord: function(e) {
    let type = e.currentTarget.dataset.type;
    let recordUrl = that.data.fileUrl + (type == 'reply' ? that.data.replybean.record.tempFilePath : that.data.question.qrecord.tempFilePath);
    if (isVoicePlaying) {
      if (recordUrl == lastPlayedVoiceUrl) {
        that.innerAudioContext.pause();
        isVoicePlaying = false;
      } else {
        that.innerAudioContext.stop();
        isVoicePlaying = true;
        lastPlayedVoiceUrl = recordUrl;
        //
        that.innerAudioContext.src = recordUrl;
        that.innerAudioContext.play();
      }
    } else {
      isVoicePlaying = true;
      if (recordUrl == lastPlayedVoiceUrl) {
        that.innerAudioContext.play();
      } else {
        lastPlayedVoiceUrl = recordUrl;
        //
        that.innerAudioContext.src = recordUrl;
        that.innerAudioContext.play();
      }
    }
    console.log(recordUrl)


  },

})